package com.example.demo.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.domin.entity.User;
import com.example.demo.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

public class SecurityUserProvider implements AuthenticationProvider {


    UserMapper userMapper;

    BCryptPasswordEncoder bCryptPasswordEncoder;

    public SecurityUserProvider(UserMapper userMapper, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userMapper = userMapper;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UserAuthentication userAuthentication = (UserAuthentication) authentication;
        Object principal = userAuthentication.getPrincipal();
        Object credentials = userAuthentication.getCredentials();
        if (!(principal instanceof String && credentials instanceof String)){
            throw new RuntimeException("传参错误");
        }
        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("username", principal.toString()));
        if (users.size()<1){
            throw new RuntimeException("用户不存在");
        }
        User user = users.get(0);
        boolean b = bCryptPasswordEncoder.matches(credentials.toString(), user.getPassword());

        if (b){
            userAuthentication.setUserId(user.getUserId());
            userAuthentication.setAuthenticated(true);
            return userAuthentication;
        }else {
            return null;
        }

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UserAuthentication.class.isAssignableFrom(authentication);
    }
}
